<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2018/7/17
 * Time: 10:01
 */
namespace app\home\controller;
use think\Db;
use think\Config;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use think\Controller;
class Common extends Controller
{
//    public function _initialize()
//    {
//        if(!session('wechat_user')){
//            $this->getOpenid();
//        }
//    }
    /**
     * 获取时间
     * @return array
     */
    public function getDateBytimeDate($string){
        $replacement = '-';
        $replacement2 = ':';
        $a = substr_replace($string, $replacement, 4, 0);
        $b = substr_replace($a, $replacement, 7, 0);
        $c = substr_replace($b, ' ', 10, 0);
        $d = substr_replace($c, $replacement2, 13, 0);
        $e = substr_replace($d, $replacement2, 16, 0);
        return $e;
    }
    /**
     *  TODO 将我的未支付的订单删掉并且库存改回去
     * param $user_id
     */
    public function updateOneToDel($user_id)
    {
        $today = date('Y-m-d H:i:s');
        $deltime = date("Y-m-d H:i:s",(strtotime("{$today}")-1800));
        $order = Db::table('up_order')
            ->where('order_userid',$user_id)
            ->where('order_status',1)
            ->where('order_time','<=',$deltime)
            ->column('order_id');
        if($order){
            foreach ($order as $v){
                $infos = Db::table('up_order_info')->alias('o')
                    ->join('up_goods g','o.oi_good_id=g.g_id','LEFT')
                    ->where('oi_order_id',$v)
                    ->field('g_stock,g_id,oi_num')
                    ->select();
                //------------TODO 加库存
                foreach ($infos as $v2){
                    if($v2['g_stock'] != -1){
                        Db::table('up_goods')
                            ->where('g_id',$v2['g_id'])
                            ->setInc('g_stock',$v2['oi_num']);
                    }
                }
                //------------------
            }
            Db::table('up_order')
                ->where('order_id','in',$order)
                ->delete();
        }
        return true;
    }
    /**
     * uploadLocality图片上传至本地&压缩
     */
    public function uploadLocality(){
        $file = request()->file('image');
        $dir = ROOT_PATH . 'public' . DS . 'uploads/images';
        if(!file_exists($dir)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($dir, 0700,true);
        }
        $url =  "http://".$_SERVER['HTTP_HOST'];
        $info = $file->validate(['size'=>2048*1024*2,'ext'=>'jpg,png,jpeg'])->move($dir);
        if($info){
            $newName = $info->getSaveName();
            //压缩图片
            image_png_size_add(ROOT_PATH . 'public' . DS . 'uploads/images/'.$newName,ROOT_PATH . 'public' . DS . 'uploads/images/'.$newName);
            echo "{$url}/uploads/images/{$newName}";
        }else{
            return json(['code'=>100,'msg'=>$file->getError()]);
        }
    }
    /**
     * 云之讯发送短信
     * @param $phone
     * @param $num
     * @return mixed
     */
    public function duaxin($phone,$num){
        $body_json = array(
            'sid'=>'2b6e76df39bef2e4a99eee7b77225c91',
            'token'=>'26a41e1a5b90f6a0bd2e4fb4fb6a713e',
            'appid'=>'760e6b2f0a45439585835cbed2e12e18',
            'templateid'=>'373248',
            'param'=>$num,
            'mobile'=>$phone,
            'uid'=>'',
        );
        $body = json_encode($body_json);
        $header = array(
            'Accept:application/json',
            'Content-Type:application/json;charset=utf-8',
        );
        $url = 'https://open.ucpaas.com/ol/sms/sendsms';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$body);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result,true);
        return $res;
    }
    function getIP()
    {
        global $ip;
        if (getenv("HTTP_CLIENT_IP"))
            $ip = getenv("HTTP_CLIENT_IP");
        else if(getenv("HTTP_X_FORWARDED_FOR"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if(getenv("REMOTE_ADDR"))
            $ip = getenv("REMOTE_ADDR");
        else $ip = "Unknow";
        return $ip;
    }
    /**
     * 获取用户openid
     */
    public function getOpenid()
    {
        $config = Config::get('wechat');
        $config['oauth'] = [
            'scopes' => ["snsapi_userinfo"],
            'callback' => '/home/Common/callback',//
        ];
        Config::set('wechat',$config);
        $app = new Application($config);
        $oauth = $app->oauth;
        // 未登录
        if (empty(session('wechat_user')['avatar'])) {
            $oauth->redirect()->send();
            // 这里不一定是return，如果你的框架action不是返回内容的话你就得使用;
            // $oauth->redirect()->send();
        } else {
            $data = array();
            $data['user_openid'] = session('wechat_user')['id'];
            return $data['user_openid'];
        }
    }

    public function callback()
    {
        $config = Config::get('wechat');
        $app = new Application($config);
        $oauth = $app->oauth;
        $user = $oauth->user();
        session('wechat_user',$user->toArray());
        header('location:'. session('target_url'));
    }

    public  function checkAll(){//$uid,$time,$value
        header("Access-Control-Allow-Origin:*");
        $today = date('Y-m-d');
        $insert = Db::table('up_goods')
            ->where('g_kill_end','<',$today)
            ->where('g_prcie_kill','>',0)
            ->where('g_status',1)
            ->field('g_name,g_id,g_price_before,g_price_now,g_prcie_kill,g_kill_end,g_kill_start,g_time')
            ->select();
        if($insert){
            Db::table('up_goods_kill')->insertAll($insert);
            Db::table('up_goods')
                ->where('g_kill_end','<',$today)
                ->where('g_prcie_kill','>',0)
                ->where('g_status',1)
                ->update(['g_prcie_kill'=>0]);
        }
        return true;
    }
}